import { useRequest } from "../../../utils/request";

const WeValidator = require('../../../package/we-validator.min')

Component({
    properties: {},
    data: {},
    methods: {
        onLoad() {
            this.request = new useRequest('api/addlivepeoplemsg', {
                hold: true
            }, this)
            this.editRequest = new useRequest('api/editlivepeople', {
                hold: true
            }, this)

            this.validatorInstance = new WeValidator({
                rules: {
                    name: {
                        required: true,
                        chinese: true
                    },
                    card_number: {
                        required: true,
                        idcard: true
                    },
                    phone: {
                        required: true,
                        mobile: true
                    }
                },
                messages: {
                    name: {
                        required: '请输入姓名',
                        chinese: '请输入正确的姓名'
                    },
                    card_number: {
                        required: '请输入身份证',
                        idcard: '请输入正确的身份证'
                    },
                    phone: {
                        required: '请输入手机号',
                        mobile: '请输入正确的手机号'
                    }
                },
            })

            // 编辑
            const eventChannel = this.getOpenerEventChannel()
            eventChannel.on('getEditPeople', data => {
                this.setData({
                    ...data
                })
            })
        },
        /**
         * 提交
         * @param e
         */
        submit(e) {
            const value = e.detail.value
            const eventChannel = this.getOpenerEventChannel()

            if (this.validatorInstance.checkData(value)) {
                if (this.data.name) {
                    this.editRequest.run({
                        ...value,
                        user_id: this.data.user_id
                    }).then(() => {
                        eventChannel.emit('editPeople', {
                            ...value,
                            user_id: this.data.user_id
                        })
                        wx.navigateBack()
                    })
                } else {
                    this.request.run(value).then((data) => {
                        eventChannel.emit('addPeople', {
                            ...value,
                            user_id: data.user_id
                        })
                        wx.navigateBack()
                    })
                }
            }
        },
    }
});
